/*
 www.thomasmueller.ch

 Copyright (C) 2004 Thomas Mueller

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

 */

package ch.thomasmueller.saltyfiles.transformer;


import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;






/**
 * This class is used to transform the data form encrypted to decrypted or vice
 * versa. <b>DESede/CBC/PKCS5Padding </b> is used as algorithm.
 * 
 * @author Martijn Sneujink, Erik Huijbers
 *  
 */
public class TripleDES extends Transformer
{

	public TripleDES(char[] aPassoword, byte[] someSalt) {
		super(aPassoword, someSalt);
		algorithm = "DESede/CBC/PKCS5Padding";
	}
	

	protected Cipher initCipher(int mode) throws Exception
	{
		String pwd = password.toString();
		
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(pwd.getBytes("UTF-8"), 0, password.length);
	
        byte[] rawKey = md.digest();
        byte[] finalKey = Arrays.copyOf(rawKey, 24); 
        //gets the first 24bytes aka 192bits
        
        DESedeKeySpec keySpec = new DESedeKeySpec(finalKey);
		
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		SecretKey key = keyFactory.generateSecret(keySpec);
		
		IvParameterSpec paramSpec = new IvParameterSpec(salt);
		
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(mode, key, paramSpec);
		return cipher;
	}

}